import {
  createStore
} from 'vuex'
import axios from 'axios'
import persist from 'vuex-persistedstate'
export default createStore({
  state: {
    objList: [],
    filterObj: [],
    flag: false,
    editFlag: false,
    filterValue: ''
  },
  mutations: {
    pushList(state, value) {
      state.objList = value
    },
    check(state, value) {
      state.objList.forEach(item => {
        if (item.id == value.id) {
          item.checked = !item.checked
        }
      })
      state.flag = state.objList.every(item => item.checked)
    },
    filterList(state, value) {
      state.filterValue = value
    },
    checkAll(state, value) {
      state.objList.forEach(item => {
        item.checked = value
      })
    },
    editFlagBtn(state, value) {
      state.editFlag = !state.editFlag
    },
    removeCheck(state, value) {
      state.filterObj = state.filterObj.filter(item => !item.checked)
    },
    fileterBtnok(state) {
      state.filterObj = state.objList.filter(item => {
        return item.name.includes(state.filterValue)
      })
    }

  },


  actions: {
    dataList(state) {
      axios.get('data.json').then(res => {
        state.commit('pushList', res.data.cartData)
        state.commit('fileterBtnok', '')
        console.log(state.filterObj);
      })
    }

  },

  getters: {
    total(state) {
      return state.objList.reduce((nums, item) => nums += item.num && item.checked, 0)
    },
    microscope(state) {
      return state.objList.reduce((nums, item) => nums += item.checked && item.num * item.price, 0)
    },
    trueLength(state) {
      return state.objList.reduce((nums, item) => nums += item.checked, 0)
    }
  },
  plugins: [persist()]


})